package com.example.design.c.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * 迭代器模式
 */
public class IteratorPattern {
    public static void main(String[] args) {
        Aggregate ag = new ConcreteAggregate();
        ag.add("中山大学");
        ag.add("华南理工");
        ag.add("韶关学院");
        System.out.print("聚合的内容有：");
        Iterator it = ag.getIterator();
        while (it.hasNext()) {
            Object ob = it.next();
            System.out.print(ob.toString() + "\t");
        }
        Object ob = it.first();
        System.out.println("\nFirst：" + ob.toString());
    }
}

//抽象聚合
interface Aggregate {

    public void add(Object object);

    public void remove(Object object);

    public Iterator getIterator();
}

//具体聚合
class ConcreteAggregate implements Aggregate {

    private List<Object> list = new ArrayList<Object>();

    @Override
    public void add(Object object) {

        list.add(object);
    }

    @Override
    public void remove(Object object) {

        list.remove(object);
    }

    @Override
    public Iterator getIterator() {

        return new ConcreteItator(list);
    }
}

//抽象迭代器
interface Iterator {

    Object first();

    Object next();

    boolean hasNext();

}

//具体迭代器
class ConcreteItator implements Iterator {

    private List<Object> list = null;

    private  int index = -1;

    public ConcreteItator(List<Object> list) {
        this.list = list;
    }

    @Override
    public Object first() {
        index = 0;
        Object obj = list.get(index);
        return obj;
    }

    @Override
    public Object next() {
        Object obj = null ;
        if(this.hasNext()){
            obj = list.get(++index);
        }
        return obj;
    }

    @Override
    public boolean hasNext() {
        if(index<list.size()-1){
            return true;
        }else {
            return false;
        }
    }
}